package com.example.turncardapp

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        // 处理系统边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // Find text views to be updated when result returns
        val tvName = findViewById<TextView>(R.id.textView1)
        val tvGender = findViewById<TextView>(R.id.textView2)
        val tvStudent = findViewById<TextView>(R.id.textView3)
        val tvPhone = findViewById<TextView>(R.id.textView4)
        val tvEmail = findViewById<TextView>(R.id.textView5)
        val tvHobby = findViewById<TextView>(R.id.textView6)
        val ivAvatar = findViewById<android.widget.ImageView>(R.id.imageView3)
        val tvMaxScore = findViewById<TextView>(R.id.textView7)

        // Preserve original labels (so we can append returned values without overwriting the prompt)
        val labelName = getString(R.string.hint_name)
        val labelGenderText = getString(R.string.label_gender)
        val labelStudent = getString(R.string.hint_student)
        val labelPhone = getString(R.string.hint_phone)
        val labelEmail = getString(R.string.hint_email)
        val labelHobby = getString(R.string.label_hobby)
        val labelMax = getString(R.string.maxScore)

        // Load saved profile from SharedPreferences and show on startup (preserve labels)
        val prefs = getSharedPreferences("profile", MODE_PRIVATE)
        // If there is saved avatar, decode and show
        prefs.getString("avatar_base64", null)?.let { encoded ->
            try {
                val decoded = android.util.Base64.decode(encoded, android.util.Base64.DEFAULT)
                val bmp = android.graphics.BitmapFactory.decodeByteArray(decoded, 0, decoded.size)
                ivAvatar.setImageBitmap(bmp)
            } catch (_: Exception) { }
        }

        // Load and show saved game max score (from separate prefs)
        val gamePrefs = getSharedPreferences("game_prefs", MODE_PRIVATE)
        val savedMax = gamePrefs.getInt("game_max_score", 0)
        tvMaxScore.text = if (savedMax > 0) "$labelMax $savedMax" else labelMax

        fun formatHobbiesFromString(hobbiesCsv: String?): String {
            if (hobbiesCsv.isNullOrBlank()) return labelHobby
            val items = hobbiesCsv.split(",").map { it.trim() }.filter { it.isNotEmpty() }
            if (items.isEmpty()) return labelHobby
            // return inline comma-separated list after the label
            val csv = items.joinToString(separator = ", ")
            return "$labelHobby $csv"
        }

        val savedName = prefs.getString("name", "")
        tvName.text = if (!savedName.isNullOrBlank()) "$labelName $savedName" else labelName

        val savedStudent = prefs.getString("student", "")
        tvStudent.text = if (!savedStudent.isNullOrBlank()) "$labelStudent $savedStudent" else labelStudent

        val savedPhone = prefs.getString("phone", "")
        tvPhone.text = if (!savedPhone.isNullOrBlank()) "$labelPhone $savedPhone" else labelPhone

        val savedEmail = prefs.getString("email", "")
        tvEmail.text = if (!savedEmail.isNullOrBlank()) "$labelEmail $savedEmail" else labelEmail

        val savedGender = prefs.getString("gender", "")
        val displayGender = when (savedGender) {
            "male" -> getString(R.string.male)
            "female" -> getString(R.string.female)
            else -> ""
        }
        tvGender.text = if (displayGender.isNotBlank()) "$labelGenderText $displayGender" else labelGenderText

        val savedHobbiesCsv = prefs.getString("hobbies", "")
        tvHobby.text = formatHobbiesFromString(savedHobbiesCsv)

        // Register for activity result to receive data back from MainActivity2
        val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                data?.let {
                    // Append returned values after the preserved labels (avoid overwriting the prompt text)
                    val name = it.getStringExtra("name")
                    tvName.text = if (!name.isNullOrBlank()) "$labelName $name" else labelName

                    val student = it.getStringExtra("student")
                    tvStudent.text = if (!student.isNullOrBlank()) "$labelStudent $student" else labelStudent

                    val phone = it.getStringExtra("phone")
                    tvPhone.text = if (!phone.isNullOrBlank()) "$labelPhone $phone" else labelPhone

                    val email = it.getStringExtra("email")
                    tvEmail.text = if (!email.isNullOrBlank()) "$labelEmail $email" else labelEmail

                    // gender stored as "male"/"female"; convert to display and append
                    val gender = it.getStringExtra("gender") ?: ""
                    val displayGenderRes = when (gender) {
                        "male" -> getString(R.string.male)
                        "female" -> getString(R.string.female)
                        else -> ""
                    }
                    tvGender.text = if (displayGenderRes.isNotBlank()) "$labelGenderText $displayGenderRes" else labelGenderText

                    // Prefer returned ArrayList<String> for hobbies, fallback to CSV
                    val hobbyList = it.getStringArrayListExtra("hobbies_list")
                    if (hobbyList != null && hobbyList.isNotEmpty()) {
                        val csv = hobbyList.joinToString(separator = ", ")
                        tvHobby.text = "$labelHobby $csv"
                    } else {
                        val hobbiesCsv = it.getStringExtra("hobbies")
                        tvHobby.text = formatHobbiesFromString(hobbiesCsv)
                    }

                    // Also update SharedPreferences to keep main page and storage consistent
                    prefs.edit().apply {
                        name?.let { putString("name", it) }
                        student?.let { putString("student", it) }
                        phone?.let { putString("phone", it) }
                        email?.let { putString("email", it) }
                        putString("gender", gender)
                        // update hobbies csv
                        val hobbiesCsv = it.getStringExtra("hobbies") ?: (hobbyList?.joinToString(",") ?: "")
                        putString("hobbies", hobbiesCsv)
                        // handle avatar bytes if present
                        it.getByteArrayExtra("avatar_bytes")?.let { bytes ->
                            val encoded = android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
                            putString("avatar_base64", encoded)
                            // update UI avatar immediately
                            try {
                                val bmp = android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                                ivAvatar.setImageBitmap(bmp)
                            } catch (_: Exception) { }
                        }
                        apply()
                    }
                }
            }
        }

        // Register launcher for MainActivity3 (game) results
        val launcherGame = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                data?.let {
                    val max = it.getIntExtra("maxScore", -1)
                    if (max >= 0) {
                        tvMaxScore.text = "$labelMax $max"
                        // persist it
                        val gp = getSharedPreferences("game_prefs", MODE_PRIVATE)
                        gp.edit().putInt("game_max_score", max).apply()
                    }
                }
            }
        }

        // 找到两个按钮并设置点击事件
        val button1 = findViewById<Button>(R.id.button1)
        val button2 = findViewById<Button>(R.id.button2)

        button1.setOnClickListener {
            // 跳转到 MainActivity2 using Activity Result API
            val intent = Intent(this, MainActivity2::class.java)
            launcher.launch(intent)
        }

        button2.setOnClickListener {
            // 跳转到 MainActivity3 using launcherGame
            val intent = Intent(this, MainActivity3::class.java)
            launcherGame.launch(intent)
        }
    }
}